package com.google.code.sysarch.v4.sound;

import java.nio.FloatBuffer;
import java.nio.IntBuffer;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.openal.AL;
import org.lwjgl.openal.AL10;
import org.lwjgl.util.WaveData;


public class Sound extends Thread {
	
	boolean running = true;

	IntBuffer buffer = BufferUtils.createIntBuffer(1);
 	IntBuffer source = BufferUtils.createIntBuffer(1);
  	FloatBuffer sourcePos = BufferUtils.createFloatBuffer(3).put(new float[] { 0.0f, 0.0f, 0.0f });
  	FloatBuffer sourceVel = BufferUtils.createFloatBuffer(3).put(new float[] { 0.0f, 0.0f, 0.0f });
  	FloatBuffer listenerPos = BufferUtils.createFloatBuffer(3).put(new float[] { 0.0f, 0.0f, 0.0f });
  	FloatBuffer listenerVel = BufferUtils.createFloatBuffer(3).put(new float[] { 0.0f, 0.0f, 0.0f });
  	FloatBuffer listenerOri = BufferUtils.createFloatBuffer(6).put(new float[] { 0.0f, 0.0f, -1.0f,  0.0f, 1.0f, 0.0f });  

  	
	Sound() {
    	sourcePos.flip();
    	sourceVel.flip();
    	listenerPos.flip();
    	listenerVel.flip();
    	listenerOri.flip();
    	
		try {
			AL.create(null, 15, 22050, true);
		} catch (LWJGLException le) {
			le.printStackTrace();
			return;
		}
		AL10.alGetError();
		if(loadALData() == AL10.AL_FALSE) {
			System.out.println("Fehler beim Laden der Daten.");
			return;
		}
		setListenerValues();
		run();
	}

	
	void setListenerValues() {
		AL10.alListener(AL10.AL_POSITION, listenerPos);
		AL10.alListener(AL10.AL_VELOCITY, listenerVel);
		AL10.alListener(AL10.AL_ORIENTATION, listenerOri);
	}
	
	
	void killALData() {
		AL10.alDeleteSources(source);
		AL10.alDeleteBuffers(buffer);
	}
	
	
	void play() {
		AL10.alSourcePlay(source.get(0));
	}
	
	void setPosition(float x, float y, float z) {
		sourcePos = BufferUtils.createFloatBuffer(3).put(new float[] { 0.0f, 0.0f, 0.0f });
	}

	
	public void run() {
		while (running) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		killALData();
	}

	int loadALData() {
		AL10.alGenBuffers(buffer);
		if (AL10.alGetError() != AL10.AL_NO_ERROR) return AL10.AL_FALSE;
		WaveData waveFile = WaveData.create("res/sound/explosive_chase_soundpack_v2.0/30mmc3.wav");
		AL10.alBufferData(buffer.get(0), waveFile.format, waveFile.data, waveFile.samplerate);
		waveFile.dispose();
		AL10.alGenSources(source);
		if (AL10.alGetError() != AL10.AL_NO_ERROR) return AL10.AL_FALSE;
		AL10.alSourcei(source.get(0), AL10.AL_BUFFER, buffer.get(0));
		AL10.alSourcef(source.get(0), AL10.AL_PITCH, 1.0f);
		AL10.alSourcef(source.get(0), AL10.AL_GAIN, 1.0f);
		AL10.alSource (source.get(0), AL10.AL_POSITION, sourcePos);
		AL10.alSource (source.get(0), AL10.AL_VELOCITY, sourceVel);
		if (AL10.alGetError() == AL10.AL_NO_ERROR) return AL10.AL_TRUE;
		return AL10.AL_FALSE;
	}
	
}
